<template>
  <el-dialog
    title="修改头像"
    :visible.sync="visibleDialog"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    width="400px"
    @open="handleOpen"
  >
    <div class="text-center">
      <crop-image-upload :image="avatar" :width="100" :height="100" :upload="handleUpload" @change="changeImage"/>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="btnSaveLoading" @click="handleSave">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import UserService from '@/api/UserService'
import UploadService from '@/api/UploadService'
import CropImageUpload from '@/components/Upload/CropImageUpload'

export default {
  components: {CropImageUpload},
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      btnSaveLoading: false,
      avatar: this.$store.state.user.userAvatar
    }
  },
  computed: {
    visibleDialog: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
    // ...mapGetters([
    //   'userAvatar'
    // ])
  },
  methods: {
    handleOpen() {
      this.avatar = this.$store.state.user.userAvatar
    },
    /**
     * 开始上传
     * @param file {File}
     */
    handleUpload(file) {
      return UploadService.uploadUserAvatar(file)
      //   .then(result => result
      //   .dataFirst(row => onSuccess(row))
      //   .ifFailure(() => onError(`文件上传失败:${result.message}`))
      //   .ifDataEmpty(() => onError('文件上传成功，但服务器未返回文件信息'))
      // )
    },
    handleCancel() {
      this.visibleDialog = false
    },
    changeImage(file) {
      this.avatar = file
    },
    async handleSave() {
      if (!this.avatar) {
        this.$message.error('请选择头像')
        return
      }
      this.btnSaveLoading = true
      const result = await UserService.changeAvatar(this.avatar).finally(() => (this.btnSaveLoading = false))
      result
        .ifToastMessage('头像修改成功', '头像修改失败')
        .ifSuccess(() => {
          this.$store.commit('user/SET_AVATAR', this.avatar)
          this.handleCancel()
          this.$emit('ok')
        })
    }
  }
}
</script>
<style scoped>
</style>
